import { assetManager, AudioClip, AudioSource, director, Node } from "cc";
import speech from "./SpeechCtrl";

const token = "";

class TtsCtrl  {
    private audio: HTMLAudioElement | null = null;
    private isPlaying: boolean = false;
    sound:AudioSource = null;
    private audioURL = null;
    init() {
        // 初始化audio对象
        const au = new Node()
        director.getScene().addChild(au)
        this.sound = au.addComponent(AudioSource);
        this.sound.node.on(AudioSource.EventType.ENDED, ()=>{
            this.handleAudioEnded();
        }, this);
  
    }


    async play(tex){
        if(!this.sound){
            this.init();
        }
        if (this.isPlaying) {
            // 如果当前有音频正在播放，停止它
            this.sound.pause();
            this.handleAudioEnded();
        }

        try {
            const res = await this.getBaiduTTS(tex, 3);
            this.playAudioFromBuffer(res);

        } catch (error) {
            console.error('播放音频失败:', error);
            // 处理错误的逻辑
        }
    }

    playAudioFromBuffer(buffer:ArrayBuffer) {
        // 使用 ArrayBuffer 创建一个 AudioClip 对象
        let blob = new Blob([buffer], { type: 'audio/mp3' });
        // 创建一个URL对象
        let audioURL = URL.createObjectURL(blob);
        // 使用cc.assetManager加载这个URL
        assetManager.loadRemote(audioURL, { ext: '.mp3' }, (_, clip: AudioClip) => {
            this.sound/* AudioSource */.clip = clip;
            this.sound.play();
            // 用完回收
            URL.revokeObjectURL(audioURL);
        });
    }
    private handleAudioEnded() {
        // 释放对象URL以避免内存泄漏
           const clip = this.sound.clip;
            if(clip!=null){
                clip.destroy();
            }
            this.sound.clip = null;
            speech.setPlaying(false);
            // 更新播放状态
            this.isPlaying = false;
    }

    async  getBaiduTTS(tex: string, cuid: any): Promise<ArrayBuffer> {
        // 对文字内容进行URL编码
        const tok = token + 99777;
        const encodedTex = encodeURIComponent(tex);
        const url = `https://tsn.baidu.com/text2audio?tex=${encodedTex}&lan=zh&cuid=${cuid}&ctp=1&aue=3&per=103&spd=6&pit=7&tok=${tok}`;
        // 发送GET请求获取TTS服务的响应
        const response = await fetch(url, {
            method: 'GET', // or 'POST' if required
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Accept': '*/*'
            }
          });

        // 检查响应状态
        if (!response.ok) {
          throw new Error(`Error: ${response.status}`);
        }
        // 获取并返回响应的ArrayBuffer
        return response.arrayBuffer();
      }

  

}

const tts = new TtsCtrl;

export default tts;
